import nme.Assets;
import nme.display.Sprite;
import nme.display.Bitmap;
import nme.display.BitmapData;
import nme.display.Graphics;
import nme.display.BlendMode;

import nme.geom.Rectangle;
import nme.geom.Matrix;
import nme.geom.Point;
import nme.geom.ColorTransform;

import nme.display.Tilesheet;

class SpriteData
{
	public var _id:String;
	public var _name:String;
	public var _src:BitmapData;
	public var _modules:Map <String, ModuleData>;
	public var _frames:Map <String, FrameData>;
	public var _anims:Map <String, AnimData>;
	public var _tileSheet (default, null):Tilesheet;
	
	private function new (id:String, name:String)
	{
		_id = id;
		_name = name;
		_modules = new Map <String, ModuleData> ();
		_frames = new Map <String, FrameData> ();
		_anims = new Map <String, AnimData> ();
	}
	
	public static function create (spriteXml:Xml):SpriteData
	{
		var sprite:SpriteData = new SpriteData (spriteXml.get("id"), spriteXml.get("name"));
		sprite._src = Assets.getBitmapData ("assets/" + spriteXml.get("src"));
		sprite._tileSheet = new Tilesheet (sprite._src);
		var modules:Iterator<Xml> = spriteXml.elementsNamed("modules").next().elementsNamed("module");
		var mId:Int = 0;
		for (m in modules)
		{
			var md:ModuleData = ModuleData.create (m, sprite);
			md.index = mId++;
			sprite._tileSheet.addTileRect (md.bound);
			sprite._modules.set (md.name, md);
		}
		
		var frames:Iterator<Xml> = spriteXml.elementsNamed("frames").next().elementsNamed("frame");
		for (f in frames)
		{
			var fd:FrameData = FrameData.create (f, sprite);
			sprite._frames.set (fd._id, fd);
		}
		
		var animations:Iterator<Xml> = spriteXml.elementsNamed("animations").next().elementsNamed("animation");
		for (a in animations)
		{
			var ad:AnimData = AnimData.create (a);
			sprite._anims.set (ad._id, ad);
		}
		
		return sprite;
	}
	
	public function getFrame (id:String):BitmapData
	{	
		var frame:FrameData = _frames.get(id);
		return frame._bitmapdata;
	}
}